package org.ihelpuoo.weboo.action.http;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;
import org.ihelpuoo.json.JSON;
import org.ihelpuoo.lang.ExceptionUtils;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.orm.filter.FieldFilter;
import org.ihelpuoo.util.PagerList;
import org.ihelpuoo.weboo.Weboo;
import org.ihelpuoo.weboo.module.ActionContext;
import org.ihelpuoo.weboo.module.AjaxException;

public abstract class AjaxAction implements Action
{

	private static final Logger	log	= Logger.getLogger(AjaxAction.class);

	public void execute(ActionContext context)
	{
		boolean fmt = context.properties().getBoolean(Weboo.FORMATTED);
		Object obj = null;
		try
		{
			obj = doAjax(context);
		}
		catch (AjaxException e)
		{
			obj = new ActionError();
			((ActionError)obj).setMessage(context.getMessage(StringUtils.trim(e.getMessage())));
			context.getResponse().setStatus(500);
		}
		catch (Throwable e)
		{
			context.getResponse().setStatus(500);
			obj = new ActionError();
			((ActionError)obj).setMessage(ExceptionUtils.dump(e));
		}

		try
		{
			if (context.getOutputType().isJson())
			{
				PrintWriter w = context.getResponse().getWriter();
				FieldFilter actived = null;
				FieldFilter locked = null;
				if (!(obj instanceof ActionError))
				{
					actived = context.properties().getPrintActivedFieldFilter();
					locked = context.properties().getPrintLockedFieldFilter();
				}
				if (obj instanceof PagerList)
					w.write(JSON.toJSONString((PagerList)obj,fmt,actived,locked));
				else
					w.write(JSON.toJSONString(obj,fmt,actived,locked));
				w.close();
			}
			else
			{
				context.getResponse().getWriter().write("Fuck XML!");
			}
		}
		catch (IOException e)
		{
			log.fatal(ExceptionUtils.dump(e));
		}
	}

	protected abstract Object doAjax(ActionContext context) throws Exception;

}
